const Category = require('../models/Category')
const Article = require('../models/Article')

exports.addCategory = async function (req, res, next) {
  let body = req.body
  console.log('body: ', body)
  try {
    await Category.create(body)
    res.success('分类添加成功')
  } catch (err) {
    next(err)
  }
}

exports.getCategoryList = async function (req, res, next) {
  try {
    const result = await Category.find().select('_id name')
    res.success(result, '获取分类列表成功')
  } catch (err) {
    next(err)
  }
}

exports.delCategory = async function (req, res, next) {
  let _id = req.params.id
  try {
    const result = await Category.findByIdAndDelete(_id)
    if (result) {
      await Article.updateMany({ category: _id }, { category: null })
    }
    res.success('分类删除成功')
  } catch (err) {
    next(err)
  }
}
exports.updateCategory = async function (req, res, next) {
  let _id = req.params.id
  let body = req.body
  try {
    await Category.findByIdAndUpdate(_id, body)
    res.success('分类更新成功')
  } catch (err) {
    next(err)
  }
}
